// pages/mall/goodsList2/index.js
const $api = require('../../../../request/api').API;
import { getDatetime, getElement, getElementDs, getElements } from '../../../../utils/util';
// import { goodsList, classifyList} from "../../../../utils/data"
const app = getApp();
const animation = wx.createAnimation({
  duration: 200
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    classifyList: [],
    beeperId: '',
    btnId: '',
    btnType: '',
    classifyIds: '',
    latitude: '',
    longitude: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    listData: [],
    businessList: [],
    businessId: '',
    businessName: '',
    businessLogo: '',
    businessIntroduce: '',
    startPrice: 0,
    tabIndex: 0,
    startPositionX: '', //滑动触屏开始的clientX位置
    startPositionY: '', //滑动触屏开始的clientY位置
    menuBtnTop: app.globalData.menuBtnTop,
    spec: {
      goodsId: '',
      showSpec: false,
      beeperId: ''
    },
    loading: true,
    fixedTop: 0, //顶部固定定位搜索的高度
    fixedTop2: 0, //搜索栏和商户的高度和
    fixedTop3: 0, //商品列表高度到顶部的距离
    fixedTop4: 0, //商户标题的底部到顶部的距离
    fixedTop5: 0, //列表到顶部的距离
    fixedTop6: 0,
    shopCartPosition: '',
    animation: '',
    addAnimation: '',
    businessClassifyList: [],
    hiddeList: false,
    businessClassifyId: '',
    viewId: '',
    sideScrollTop: '',
    listScrollTop: '',
    sideScroll: false,
    listScroll: false,
    startIndex: 0,
    endIndex: 20,
    // height: 0,
    show: true, //是否显示与隐藏顶部的商户图片
    showDot: false,
    dotClientX: '',
    dotClientY: '',
    pageScroll: false,
    openIntroduce: [],
    activeShow: false,
    activeList: [],
    activeItem: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // 清掉备注
    app.globalData.recordRemark = '';
    app.globalData.remark = '';
    let beeperId = app.globalData['btnList.beeperId'];
    if (app.globalData.shopBeeperId != beeperId) {
      // 进来的时候如果不是与之前相同的呼叫器就清空之前先清空购物车
      wx.setStorageSync('shopCartData', JSON.stringify([]));
    }
    app.globalData.shopBeeperId = beeperId;
    let latitude = app.globalData['btnList.latitude'];
    let longitude = app.globalData['btnList.longitude'];
    let provinceName = app.globalData['btnList.provinceName'];
    let cityName = app.globalData['btnList.cityName'];
    let areaName = app.globalData['btnList.areaName'];
    let btnId = app.globalData['btnList.btnId'];
    let btnType = app.globalData['btnList.btnType'];
    let classifyIds = app.globalData['btnList.btnServerClassifyIds'];
    let queryType = app.globalData['btnList.queryType'];
    this.data.spec.beeperId = beeperId;
    if (btnId) {
      this.setData({
        spec: this.data.spec,
        btnId: btnId,
        beeperId: beeperId ? beeperId : '',
        classifyIds: classifyIds,
        btnType: btnType,
        queryType: queryType,
        latitude: latitude ? parseFloat(latitude) : '',
        longitude: longitude ? parseFloat(longitude) : '',
        provinceName: provinceName,
        cityName: cityName,
        areaName: areaName
      });
      await this.initGetStyle();
      await this.getBusinessList();
      this.getStyle();
    }

    wx.nextTick(() => {
      this.setData({
        pageScroll: true
      });
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 每一次进来的时候都需要根据本地存储的购物车来修改列表中商品的数量
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    this.data.listData.forEach(item => {
      item.nums = 0;
      shopCartList.forEach(item2 => {
        if (item.variantId == item2.variantId) {
          item.nums = item2.nums;
        }
        if (item.goodsId == item2.goodsId && !item.variantId) {
          item.nums = item.nums + item2.nums;
        }
      });
    });

    const { businessId } = app.globalData;
    // 这里如果存在商户id就需要跳到目标商户去
    if (businessId) {
      const e = {};
      e.detail = { name: businessId };
      this.businessChange(e);
      delete app.globalData.businessId;
    }
    this.setData({
      listData: this.data.listData
    });
  },
  async initGetStyle() {
    const res = await getElement('.top-fixed');
    this.setData({
      fixedTop: res[0].bottom
    });
  },
  getStyle() {
    const { fixedTop } = this.data;
    wx.nextTick(() => {
      getElementDs(['.business-wrapper', '.business-info', '.silder-wrapper', '#balance>>>.shop-cart-img']).then(
        res => {
          this.setData({
            fixedTop2: fixedTop + res[0].height,
            fixedTop3: res[0].top,
            fixedTop4: res[1].bottom,
            fixedTop5: res[2].top - (fixedTop + res[0].height),
            shopCartPosition: res[3]
          });
        }
      );

      if (this.data.businessIntroduce) {
        getElement('.business-introduce').then(res => {
          this.setData({
            fixedTop6: res[0].bottom
          });
        });
      }
    });
  },
  // 返回上一页
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 阻止冒泡
  stopBubble() {},
  // 显示商户介绍
  showIntroduce(e) {
    wx.pageScrollTo({
      scrollTop: 0,
      success: () => {
        const { openIntroduce } = this.data;
        this.setData({
          openIntroduce: openIntroduce.length ? [] : ['1'],
          pageScroll: openIntroduce.length ? true : false
        });
      }
    });
  },
  // 显示活动介绍
  showActivePopup(e) {
    const { item } = e.currentTarget.dataset;
    this.setData({
      activeShow: true,
      activeItem: item
    });
  },
  closeActivePopup() {
    this.setData({
      activeShow: false
    });
  },
  // 去搜索页面
  toSearch() {
    const { businessId, startPrice } = this.data;
    let item = this.data.businessList.find(item => this.data.businessId == item.id);
    if (item.businessVillageIds && item.businessVillageIds.length > 0) {
      const businessVillageIds = item.businessVillageIds.join(',');
      wx.navigateTo({
        url:
          '/subcontract/home/pages/search/index?businessId=' +
          businessId +
          '&businessVillageIds=' +
          businessVillageIds +
          '&startPrice=' +
          startPrice
      });
    } else {
      wx.navigateTo({
        url: '/subcontract/home/pages/search/index?businessId=' + businessId + '&startPrice=' + startPrice
      });
    }
  },
  // 滚动侧边栏到
  async goodsListScroll() {
    this.recordScroll();
    const res1 = await getElements('.business-classify_name');
    const res2 = await getElements('.sidebar');
    const res3 = await getElement('#balance');
    const res4 = await getElement('.list-wrapper');
    const listTop = res4[0].top;
    const { businessClassifyList } = this.data;
    // wx.nextTick(()=>{
    if (!businessClassifyList.length) return;
    res1[0].reverse();
    res1[0].find(item => {
      if (item.top <= listTop + 5) {
        let index = businessClassifyList.findIndex(item2 => item2.id == item.id.split('a')[1]);
        this.setData({
          tabIndex: index
        });
        const top = res2[0][index].top;
        const bottom = res2[0][index].bottom;
        const firstTop = res2[0][0].top;
        const lastTop = res2[0].at(-1).top;
        if (top < listTop) {
          this.setData({
            sideScrollTop: top - firstTop + 10
          });
        } else if (bottom + 100 > res3[0].top) {
          let val = lastTop - top + listTop - firstTop;
          if (lastTop == top) {
            val = val + top;
          }
          this.setData({
            sideScrollTop: val
          });
        }
        return true;
      }
    });
  },
  // 点击右侧获取数据
  async getData(e) {
    const { id } = e.currentTarget.dataset.item;
    this.setData({
      sideScroll: true,
      listScroll: true
    });
    wx.pageScrollTo({
      scrollTop: this.data.fixedTop5,
      duration: 0
    });
    wx.nextTick(() => {
      setTimeout(() => {
        this.setData({
          viewId: 'a' + id
        });
      }, 100);
    });

    return;
  },
  // 获取商户列表
  async getBusinessList() {
    let params = {
      type: 1,
      btnId: this.data.btnId,
      beeperId: this.data.beeperId,
      btnType: this.data.btnType,
      classifyIds: this.data.classifyIds,
      queryType: this.data.queryType,
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      provinceName: this.data.provinceName,
      cityName: this.data.cityName,
      areaName: this.data.areaName
    };
    let res = await $api.getBusinessList(params);
    let data = res.data.data || [];
    if (!data.length) return;
    this.setData({
      businessList: data,
      startPrice: data.length > 0 ? data[0].startPrice : '',
      businessId: data.length > 0 ? data[0].id : '',
      businessName: data.length > 0 ? data[0].name : '',
      businessIntroduce: data.length > 0 ? data[0].introduce : '',
      businessLogo: data.length > 0 ? data[0].logo : ''
    });
    await this.getActiveList();
    await this.getBusinessClassifyList();

    if (this.selectComponent('#tabs')) this.selectComponent('#tabs').resize();
  },
  // 获取商户自定义分类
  async getBusinessClassifyList() {
    const { businessId, btnId, queryType, btnType, classifyIds, beeperId } = this.data;
    const params = {
      businessId,
      type: 1,
      btnId,
      queryType,
      btnType,
      beeperId,
      classifyIds
    };
    const res = await $api.getBusinessClassifyList(params);
    const list = res.data.data || [];
    list.forEach(item => {
      item.name = item.name.replace(/\<img/gi, '<img style="width:auto;height:17px;vertical-align:-3px"');
    });
    this.setData({
      businessClassifyList: list,
      tabIndex: 0
    });
    await this.getListData();
  },
  // 获取活动
  async getActiveList() {
    $api.getActiveList({ businessId: this.data.businessId }).then(res => {
      this.setData({
        activeList: res.data.data || []
      });
    });
  },
  // 获取商品数据
  async getListData() {
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    const { businessList, businessId, btnId, beeperId, btnType, classifyIds, queryType, businessClassifyList } =
      this.data;
    let params = {
      btnId,
      beeperId,
      btnType,
      classifyIds,
      businessId,
      queryType,
      businessClassifyIds: businessClassifyList.length ? businessClassifyList.map(item => item.id).toString() : ''
    };
    let item = businessList.find(item => businessId == item.id);
    if (item.businessVillageIds && item.businessVillageIds.length > 0) {
      params.businessVillageIds = item.businessVillageIds.join(',');
    }

    this.setData({
      loading: true
    });

    const res = await $api.getGoodsList(params);
    let data = res.data.data || [];
    if (businessClassifyList.length) {
      data = data.flatMap(item => item.list);
    }
    // 添加一个nums属性，同时判断购物车里面是否存在该商品，如果存在那么就需要把该商品的数量赋值给商品列表对应的该商品
    data.forEach(item => {
      item.nums = 0;
      shopCartList.forEach(item2 => {
        if (item.variantId == item2.variantId) {
          item.nums = item2.nums;
        }
        if (item.goodsId == item2.goodsId && !item.variantId) {
          item.nums = item.nums + item2.nums;
        }
      });
    });

    if (businessClassifyList.length) {
      // 如果商户分类存在就需要添加标题
      res.data.data.forEach(item => {
        item.list[0].businessClassifyName = businessClassifyList.find(
          item2 => item2.id == item.businessClassifyId
        ).name;
      });
    }

    // 判断是否在活动范围内
    this.activeTime(data);
    // 判断如果是商户分类第一页的数据需要添加标题
    this.setData({
      listData: data,
      startIndex: 0,
      endIndex: 20,
      loading: false,
      listScrollTop: 0
    });
    // 判断是否超时
    this.judgeTimeout();
    if (this.selectComponent('#tabs')) this.selectComponent('#tabs').resize();
  },
  // 去商品详情页面
  toGoodsDetail(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let beeperBtnId = e.currentTarget.dataset.beeperBtnId;
    wx.navigateTo({
      url: '/subcontract/home/pages/goodsDetail/index?goodsId=' + goodsId + '&beeperBtnId=' + beeperBtnId
    });
  },
  // 商户改变
  async businessChange(e) {
    const { businessList, businessId } = this.data;
    const { name } = e.detail;
    if (businessId == name) return;
    const business = businessList.find(item => item.id == name);

    this.setData({
      businessId: name,
      startPrice: business.startPrice,
      businessName: business.name,
      businessLogo: business.logo,
      businessIntroduce: business.introduce
    });
    await this.getActiveList();
    await this.getBusinessClassifyList();

    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0,
      success: async () => {
        // 每次切换商户都需要重新计算列表距离顶部的高度
        const res = await getElement('.silder-wrapper');
        this.setData({
          listScrollTop: 0,
          fixedTop5: res[0].top - this.data.fixedTop2
        });
      }
    });
  },
  // 添加
  async addNum(e) {
    // 这里有三种情况，触发该函数
    // 1.事件绑定触发
    // 2.balance组件自定义事件触发
    // 3.goods-spec组件触发
    // 如果e.detail.goodsId存在那么就表示是子组件触发的这个函数
    let obj = null;
    let variantId = null;
    let indexArr = [];
    const goodsId = e.detail.goodsId || e.currentTarget.dataset.item.goodsId;
    if (this.timeOut(goodsId)) return;
    if (e.detail.goodsId) {
      // 是goods-spec或者是balance组件调用的
      indexArr = this.getIndexsById(this.data.listData, e.detail.goodsId, 'goodsId');
      const o = this.data.listData[indexArr[0]] || {};
      obj = { ...o, ...e.detail };
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId;
      if (indexArr.length) {
        // 可能有重复的数据
        indexArr.forEach(i => {
          this.data.listData[i].nums = this.data.listData[i].nums + e.detail.nums;
        });
        this.setData({
          listData: this.data.listData
        });
      }
    } else {
      const { item } = e.currentTarget.dataset;
      // 事件绑定触发,这里需要判断有没有关联产品而且至少有没有添加一个
      let listData = this.data.listData;
      variantId = item.variantId;
      indexArr = this.getIndexsById(this.data.listData, variantId, 'variantId');
      // 如果存在关联产品拉起选择关联产品的框框
      if (this.data.beeperId && item.relationFlag && !listData[indexArr[0]].nums) {
        let spec = this.data.spec;
        spec.goodsId = item.goodsId;
        (spec.showSpec = true),
          this.setData({
            spec
          });
        return;
      } else {
        // 正常添加数据
        // 执行添加动画
        this.addAni(e.touches[0]);
        indexArr.forEach(i => {
          listData[i].nums++;
          this.setData({
            listData
          });
        });
        obj = Object.assign({ ...listData[indexArr[0]] }, { nums: 1 });
      }
      // 判断是否在活动范围之内
      const goodsList = this.data.listData.filter(item => item.goodsId == goodsId);
      if (goodsList.length) {
        this.activeTime(goodsList);
      }
    }

    // 执行父组件的addNum方法也会执行子组件的addNum方法，子组件也会执行父组件的，所以必须要用一个属性来控制，否则会陷入死循环
    if (!e.detail.flag) {
      e.flag = true;
      this.selectComponent('#balance').addNum(e, obj);
    }
  },
  // 添加动画
  addAni({ clientX, clientY }) {
    const { top, right } = this.data.shopCartPosition;
    this.setData({
      showDot: true,
      dotClientX: clientX - 4,
      dotClientY: clientY - 8
    });
    wx.nextTick(() => {
      const addAnimation = wx
        .createAnimation()
        .top(clientY - 20)
        .left(clientX - 50)
        .step({ duration: 100 })
        .top(top)
        .left(right - 12)
        .step({ duration: 100, timingFunction: 'ease-in' });
      this.setData({
        addAnimation: addAnimation.export()
      });
      setTimeout(() => {
        this.setData({
          showDot: false,
          addAnimation: null
        });
      }, 250);
    });
  },
  // 减少
  subNum(e) {
    // let index = null
    let indexArr = [];
    const goodsId = e.detail.goodsId || e.currentTarget.dataset.item.goodsId;
    if (this.timeOut(goodsId)) return;

    if (e.detail.goodsId) {
      // index = this.getIndexById(this.data.listData, e.detail.goodsId, "goodsId")
      indexArr = this.getIndexsById(this.data.listData, e.detail.goodsId, 'goodsId');
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId;
      if (indexArr.length > 0) {
        indexArr.forEach(i => {
          this.data.listData[i].nums--;
        });
        this.setData({
          listData: this.data.listData
        });
      }
    } else {
      // index = this.getIndexById(this.data.listData, e.currentTarget.dataset.item.variantId, "variantId")
      indexArr = this.getIndexsById(this.data.listData, e.currentTarget.dataset.item.variantId, 'variantId');
      indexArr.forEach(i => {
        this.data.listData[i].nums--;
      });

      this.setData({
        listData: this.data.listData
      });
    }
    const goodsList = this.data.listData.filter(item => item.goodsId == goodsId);
    if (goodsList.length) {
      this.activeTime(goodsList);
    }
    if (!e.detail.flag) {
      e.flag = true;
      this.selectComponent('#balance').subNum(e);
    }
  },
  // 清空数量
  clear() {
    this.data.listData.forEach(item => (item.nums = 0));
    this.setData({
      listData: this.data.listData
    });
  },

  // 判断哪些产品不在销售时间内
  judgeTimeout() {
    const { listData } = this.data;
    listData.forEach(item => {
      let res = null;
      if (!item.goodsHours || (item.goodsHours && !item.goodsHours.length)) {
        return;
      }
      res = item.goodsHours.some(item => {
        let time = new Date();
        let begin = new Date();
        let end = new Date();
        const arr = item.beginHours.split(':').map(item => Number(item));
        const arr2 = item.endHours.split(':').map(item => Number(item));
        begin.setHours(arr[0]);
        begin.setMinutes(arr[1]);
        end.setHours(arr2[0]);
        end.setMinutes(arr2[1]);
        return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
      });
      if (!res) {
        item.saleState = 0;
      }
    });
    this.setData({
      listData
    });
  },
  // 判断是否在时间段内，如果不在就要是售罄的
  timeOut(goodsId) {
    const { listData } = this.data;
    let goods = listData.find(item => item.goodsId == goodsId);
    if (!goods) {
      // 如果列表里面没有的话就直接添加购物车
      return false;
    }
    if (!goods.goodsHours || (goods.goodsHours && !goods.goodsHours.length)) return;
    const res = goods.goodsHours.some(item => {
      let time = new Date();
      let begin = new Date();
      let end = new Date();
      const arr = item.beginHours.split(':').map(item => Number(item));
      const arr2 = item.endHours.split(':').map(item => Number(item));
      begin.setHours(arr[0]);
      begin.setMinutes(arr[1]);
      end.setHours(arr2[0]);
      end.setMinutes(arr2[1]);
      return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
    });
    if (!res) {
      // 售罄之后改变状态同时清空购物车里面售罄的该数据
      goods.nums = 0;
      goods.saleState = 0;
      this.setData({
        listData
      });
      this.selectComponent('#balance').timeOut(goodsId);
      return true;
    } else {
      return false;
    }
  },
  //需要判断是不是活动时间
  activeTime(val) {
    val = Array.isArray(val) ? val : [val]; //拼接一个数组好计算
    val.forEach(item => {
      if (!item.active) return;
      let { beginDate, endDate, activePrice } = item.active;
      beginDate = getDatetime(beginDate).getTime();
      endDate = getDatetime(endDate).getTime();
      let nowDate = new Date().getTime();
      if (nowDate > beginDate && nowDate < endDate) {
        item.activeDiscount = parseFloat(((activePrice / item.price) * 10).toFixed(2)) || 0.01;
      } else {
        item.activeDiscount = '';
      }
    });
  },
  // 选择规格
  selectSpec(e) {
    if (this.timeOut(e.currentTarget.dataset.item.goodsId)) return;
    let item = e.currentTarget.dataset.item;
    let spec = this.data.spec;
    (spec.goodsId = item.goodsId), (spec.showSpec = true);
    this.setData({
      spec
    });
  },
  // 通过商品id来获取对应的数组索引，不存在就返回-1,prop是对应的字符串,默认是id
  getIndexById(arr, id, prop = 'id') {
    let tempIndex = -1;
    arr.find((item, index) => {
      if (item[prop] == id) {
        tempIndex = index;
        return true;
      }
    });
    return tempIndex;
  },
  //  通过商品id来获取对应的数组索引数组
  getIndexsById(arr, id, prop = 'id') {
    const res = [];
    arr.forEach((item, index) => {
      if (item[prop] == id) {
        res.push(index);
      }
    });
    return res;
  },
  // 触屏开始滑动
  silderStart(e) {
    this.setData({
      startPositionX: e.changedTouches[0].clientX,
      startPositionY: e.changedTouches[0].clientY
    });
  },
  // 触屏结束滑动
  silderEnd(e) {
    let endPositionX = e.changedTouches[0].clientX;
    let endPositionY = e.changedTouches[0].clientY;
    let tempX = endPositionX - this.data.startPositionX;
    let tempY = endPositionY - this.data.startPositionY;
    let businessList = this.data.businessList;
    let index = this.getIndexById(businessList, this.data.businessId);
    let length = this.data.businessList.length;
    // 左右滑动
    if (tempX < -45 && index + 1 <= length - 1 && Math.abs(tempY) < 25) {
      const { id, name, logo, startPrice, introduce } = businessList[index + 1];
      this.setData({
        businessId: id,
        startPrice,
        businessName: name,
        businessLogo: logo,
        businessIntroduce: introduce
      });
      this.getBusinessClassifyList();
    }
    if (tempX > 45 && index - 1 >= 0 && Math.abs(tempY) < 25) {
      const { id, name, logo, startPrice, introduce } = businessList[index - 1];
      this.setData({
        businessId: id,
        startPrice,
        businessName: name,
        businessLogo: logo,
        businessIntroduce: introduce
      });
      this.getBusinessClassifyList();
    }
  },
  // 直接下单去订单结算页面
  toSubmitOrderPage(e) {
    let item = e.currentTarget.dataset.item;
    if (item) {
      if (this.data.beeperId && item.relationFlag) {
        let spec = this.data.spec;
        spec.goodsId = item.goodsId;
        (spec.showSpec = true),
          this.setData({
            spec
          });
      } else {
        item.nums = 1;
        app.globalData.goodsList = [item];
        // item = encodeURIComponent(JSON.stringify(e.currentTarget.dataset.item))
        wx.navigateTo({
          url: '/subcontract/home/pages/submitOrder/index'
        });
      }
    }
  },
  recordScroll() {
    animation.translateX(70).step();
    this.setData({
      animation: animation.export()
    });
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      animation.translateX(0).step();
      this.setData({
        animation: animation.export()
      });
    }, 300);
  },
  // 开始录音
  recordSound() {
    this.selectComponent('#sound-record-two').start();
  },
  // 结束录音
  endSound() {
    this.selectComponent('#sound-record-two').end();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 页面滚动
   */
  onPageScroll: function (e) {
    this.recordScroll();
    const { fixedTop4, fixedTop5 } = this.data;
    const flag = e.scrollTop > fixedTop4 - 40;
    const flag2 = e.scrollTop >= fixedTop5 - 3;
    this.setData({
      show: flag ? false : true,
      listScroll: flag2 ? true : false,
      sideScroll: flag2 ? true : false
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
